<script setup>
import { ref, defineProps, defineEmits, onMounted } from 'vue';
import { customerAll, productAll, customerContact,saveContract,queryAttachmentList,queryPlanList } from "@/utils/api";
import axios from 'axios';
import { Check, Close, Delete, Edit, Message, Search, Star, Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from "element-plus";
import host from '@/utils/env.js';
import { getUser } from "@/utils/session"
//获取用户的登录信息
let user = getUser();
//声明事件 关闭事件
const emits = defineEmits(["close", "refreshData"]);

//定义属性
const props = defineProps({
    visible: {
        type: Boolean,
        required: true,
        default: false
    }
})


//定义消息框是否显示
// const visible = ref(true)

// const isjob = ref(true);//是否禁用职位下拉列表 
const nameCustomer = ref(); //存放客户名称
const nameProduct = ref(); //存放产品名称
const statusType = ref([
    { id: 1, name: "销售合同" },
    { id: 2, name: "生产合同" },

]); //显示类型
const mannerList = ref([
    { id: 1, name: "银行卡" },
    { id: 2, name: "支持宝" },
    { id: 3, name: "微信" },
])
//定义用户对象
const contract = ref({
    code: "",
    name: "",
    status: 1,
    type: 1,
    customerId: "",
    customerName: "",
    productId: "",
    productName: "",
    amount: 0.00,
    note: "",
    user: "",
    manner: 1,
    beginDate: "",
    endDate: "",
    payment: 0.00,
    userCode:user.user.code,
    attachmentList: [],
    planList:[]
});

//声明初始方法
function init(data) {
    console.log(data);
    if (data) {
        console.log("data.id=>>>",data.id);
        //data存在，说明是修改
        contract.value = data;
        queryPlan(data.id);
        queryAttachment(data.id);
    } else {
        //否则为新增，将user的值还原
        contract.value = {
            code: "",
            name: "",
            status: 1,
            type: 1,
            customerId: "",
            customerName: "",
            productId: "",
            productName: "",
            amount: 0.00,
            note: "",
            user: "",
            manner: 1,
            beginDate: "",
            endDate: "",
            payment: 0.00,
            userCode:user.user.code,
            attachmentList: [],
            planList:[]

        };
    }
}
//保存方法
function save() {
   
    let promise;
    if (contract.value.id) {
        //修改用户
        console.log("修改信息：", contract.value);
        promise = updateUser(contract.value)
    } else {
        //新增用户
        console.log("tableData>>>",plans.value);
        contract.value.planList=plans.value;
        console.log("contract.value.planList>>>>",contract.value.planList);

        promise = saveContract(contract.value)
    }
    promise.then((res) => {
        if (res.code == 1) {
            ElMessage({
                message: "保存成功",
                type: "success",
            });
            //关闭
            close();
            //通知父组件更新数据
            emits("refreshData")
        }
    })
}



//关闭弹窗时调用的方法
function close() {
    //抛出事件 父组件 同时传递值
    emits("close", false);
    contract.value = {
            code: "",
            name: "",
            status: 1,
            type: 1,
            customerId: "",
            customerName: "",
            productId: "",
            productName: "",
            amount: 0.00,
            note: "",
            user: "",
            manner: 1,
            beginDate: "",
            endDate: "",
            payment: 0.00,
            userCode:user.user.code,
            attachmentList: [],
            planList:[]

        };
        plans.value = [];
        fileList.value=[];
      
}
const customerTem = ref(); //部门列表
const productTem = ref(); //产品列表


//查询部门
async function queryCustomer() {
    const res = await customerAll();
    console.log("部门列表=====》", res);
    if (res.code == 1) {
        customerTem.value = res.data
    }
}

//查询产品列表
async function queryProduct() {
    const res = await productAll();
    console.log("产品列表=====>", res);
    if (res.code == 1) {
        productTem.value = res.data
    }
}


const userList = ref();//存放联系人列表
//当客户名称列表发生变化时
async function chg(data) {
    let tmp = await data.split("!");
    contract.value.customerId = await tmp[0];
    contract.value.customerName = await tmp[1];
    console.log("客户id和客户名称:", contract.value.customerId, contract.value.customerName);
    const res = await customerContact(contract.value.customerId);
    console.log("联系人列表====>", res);
    if (res.code == 1) {
        contract.value.user = res.data;
    }
}

function chg1(data) {
    let tmp = data.split("!");
    contract.value.productId = tmp[0];
    contract.value.productName = tmp[1];
    console.log("客户id和客户名称:", contract.value.productId, contract.value.productName);
}

const imageUrl = ref("");

const fileList = ref([]) //存储文件列表

//上传成功
 function handleAvatarSuccess(response, uploadFile) {
    console.log("response>>>>", response);
    console.log("uploadFile>>>>>", uploadFile);
    if ( response.code == 1) {
        //imageUrl.value = URL.createObjectURL(uploadFile.raw);
        fileList.value.push(uploadFile);
        const attachments = [];
        for (const file of fileList.value) {
            console.log("file>>>", file);
            // 根据上传的文件信息创建 attachment 对象
            const attachment = {
                uploadUser: user.user.name,
                filename: uploadFile.name,
                size: uploadFile.size,
                url: response.data
            };
            attachments.push(attachment)
        }
        contract.value.attachmentList.push(attachments[attachments.length - 1]);
        console.log("fileList>>>>>", fileList.value);
        console.log("contract.value.attachmentList>>>>", contract.value.attachmentList);
    } else {
        ElMessage.error(response.msg);
        imageUrl.value = "";
    }

}

//上传前
function beforeAvatarUpload(rawFile) {
    if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png" && rawFile.type !== "image/gif") {
        ElMessage.error("头像只能是jpg/png/gif格式");
        return false;
    } else if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error("头像不能超过10M");
        return false;
    }
    return true;
}
//回款计划信息
const plan = ref({
        period:1,
        manner:1,
        planTime:"",
        amount:0.00,
        ratio:"",
        reminderTime:"",
})
//表格数据
const plans = ref([])
//存储变量
const PPlan = ref([])
//增加回款计划信息
function insertPlan(){
const newPlan = {
    // 使用tableData数组的长度+1作为期数
    period: plans.value.length + 1, 
    manner: 1,
    planTime: "",
    amount: 0.00,
    ratio: "",
    reminderTime: ""
}
    plans.value.push(newPlan)
    PPlan.value.push(newPlan)
   // console.log("tableData>>>",plans.value);
   // contract.value.planList.push(plans);
   // console.log("contract.value.planList>>>>",contract.value.planList);
}

//根据合同id查询回款计款列表
const tableData = ref();
async function queryPlan(contractId){
    const res =await queryPlanList(contractId);
    if(res.code == 1){
        tableData.value = res.data;
        console.log("回款计划列表",tableData.value);
    }
}

//根据合同id查询合同附件列表
const imageList = ref();
async function queryAttachment(contractId){
    const res =await queryAttachmentList(contractId);
    if(res.code == 1){
        imageList.value = res.data;
        console.log("附件路劲表",imageList.value);
    }
}

/******************生命周期********** */
onMounted(() => {
    queryCustomer(),
        queryProduct()
});
//暴露方法
defineExpose({ init });

</script>
<template>
    <el-dialog :model-value="visible" :title="contract.id ? '查看合同' : '添加合同'" width="50%" :close-on-click-modal="false"
        @close="close" draggable>
        <!--基本信息-->
        <div class="basic">
            <div style="font-weight: bold">客户信息</div>
            <el-row>
                <el-col :span="3">合同编号:</el-col>
                <el-col :span="9">
                    <el-input v-model="contract.code" placeholder="请输入合同编号" clearable :disabled="contract.id != undefined" /></el-col>
                <el-col :span="3">合同状态:</el-col>
                <el-col :span="9">
                    <el-input placeholder="待审批" disabled />
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="3">合同名称:</el-col>
                <el-col :span="9">
                    <el-input v-model="contract.name" placeholder="请输入合同名称" clearable :disabled="contract.id != undefined" /></el-col>
                <el-col :span="3">合同类型:</el-col>
                <el-col :span="9">
                    <el-select v-model="contract.type" clearable :disabled="contract.id != undefined">
                        <el-option v-for="item in statusType" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="3">客户名称:</el-col>
                <el-col :span="9">
                    <el-select v-model="nameCustomer" clearable @change="chg" :placeholder="contract.id && contract.customerId ? contract.customerName : '请选择客户'" :disabled="contract.id">
                        <el-option v-for="item in customerTem" :key="item.id" :label="item.name"
                            :value="item.id + '!' + item.name" />
                    </el-select>
                </el-col>
                <el-col :span="3">关联产品:</el-col>
                <el-col :span="9">
                    <el-select v-model="nameProduct" clearable @change="chg1" :placeholder="contract.id && contract.productId ? contract.productName : '请选择产品'" :disabled="contract.id">
                        <el-option v-for="item in productTem" :key="item.id" :label="item.name"
                            :value="item.id + '!' + item.name" />
                    </el-select>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="3">合同金额:</el-col>
                <el-col :span="9">
                    <el-input v-model="contract.amount" placeholder="请输入合同金额" clearable  :disabled="contract.id"/>
                </el-col>
                <el-col :span="12">&nbsp;</el-col>
            </el-row>
            <el-row>
                <el-col :span="3">合同文件:</el-col>
                <el-col :span="21">
                    <template v-if="contract.id">
                            <img  v-for="item in imageList" :key="item" :src = "host+item.url" class="avatar" style="width: 100px; margin-right: 5px;" />
                    </template>
                    <template v-else>
                        <el-upload class="avatar-uploader" :ref="upload" list-type="picture-card" multiple="true" name="file"
                        :action="host + '/api_v1.0/file'" :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <el-icon  class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    </template>
                </el-col>

            </el-row>
        </div>

        <!--账号信息-->
        <div class="basic" style="margin-top: 20px">
            <div style="font-weight: bold">付款信息</div>
            <el-row>
                <el-col :span="3">签订人:</el-col>
                <el-col :span="9">
                    <el-input v-model="contract.user" placeholder="请输入签订人" clearable :disabled="contract.id"/>
                </el-col>
                <el-col :span="3">付款方式:</el-col>
                <el-col :span="9">
                    <el-select v-model="contract.manner" clearable :placeholder="contract.id && mannerList.id ? mannerList.name : '请选择产品'"  :disabled="contract.id">
                        <el-option v-for="item in mannerList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="3">签订时间:</el-col>
                <el-col :span="9">
                    <el-date-picker v-model="contract.beginDate" type="date" placeholder="选择签订时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" :disabled="contract.id" />
                </el-col>
                <el-col :span="3">预付款:</el-col>
                <el-col :span="9">
                    <el-input v-model="contract.payment" placeholder="请输入预付款" clearable :disabled="contract.id" />
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="3">到期时间:</el-col>
                <el-col :span="9">
                    <el-date-picker v-model="contract.endDate" type="date" placeholder="选择签订时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD"  :disabled="contract.id"/>
                </el-col>
                <el-col :span="3">备注:</el-col>
                <el-col :span="9">
                    <el-input v-model="contract.note" placeholder="请输入备注" clearable  :disabled="contract.id"/></el-col>
            </el-row>
        </div>
        <div class="basic" style="margin-top: 20px">
            <div style="font-weight: bold">回款计划</div>
            <el-table :data="contract.id ? tableData : plans" style="width: 100%" border>
            <el-table-column  label="期数" width="70" align="center" >
            <template v-slot="{row}">
              <el-input v-model="row.period" :disabled="contract.id" ></el-input>
            </template>
            </el-table-column>
            <el-table-column  label="计划回款时间" width="140" align="center">
            <template v-slot="{row}">
                <el-date-picker v-model="row.planTime" style="width: 120px ;" type="date" placeholder="请选择" format="YYYY-MM-DD" value-format="YYYY-MM-DD" :disabled="contract.id"/>
            </template>
            </el-table-column>
            <el-table-column  label="回款方式" width="110" align="center">
            <template v-slot="{row}">
                <el-select v-model="row.manner" clearable :disabled="contract.id">
                        <el-option v-for="item in mannerList" :key="item.id" :label="item.name" :value="item.id"  />
                    </el-select>
            </template>
            </el-table-column>
            <el-table-column  label="回款金额" width="120" align="center">
            <template v-slot="{row}">
                <el-input v-model="row.amount"  :disabled="contract.id"></el-input>
            </template>
            </el-table-column>
            <el-table-column  label="回款回款比例" width="120" align="center">
            <template v-slot="{row}">
                <el-input v-model="row.ratio" placeholder="自动计算" disabled></el-input>
            </template>
            </el-table-column>
            <el-table-column  label="提醒时间" align="center">
            <template v-slot="{row}">
                <template v-if="contract.id">
                    <el-input v-model="row.day" disabled></el-input>
                </template>
                <template v-else>
                    <el-date-picker v-model="row.reminderTime" style="width: 120px ;" type="date" placeholder="请选择" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                </template>
            </template>
            </el-table-column>
        </el-table>
         <el-button :disabled="contract.id" type="info" :icon="Plus" style="width: 100%;" @click="insertPlan">新增计划</el-button>   
        </div>

        <!--按钮-->
        <div class="btn">
            <el-button type="primary" @click="save">保存</el-button>
            <el-button style="margin-left: 60px" @click="close">取消</el-button>
        </div>
    </el-dialog>
</template>
<style scoped>
.basic {
    width: 100%;
    border: #eee solid 1px;
    padding: 5px;
}

:deep(.el-row) {
    display: flex;
    align-items: center;
    margin: 15px 0;
}

:deep(.el-col-3) {
    text-align: center;
}

.btn {
    text-align: center;
    margin-top: 20px;
}



:deep( .el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}
</style>